package com.rabbitmq.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.sun.org.apache.xpath.internal.functions.FuncFalse;

import java.io.IOException;
import java.util.Calendar;
import java.util.concurrent.TimeoutException;

/**
 * 王琦
 * 2021/10/31
 */
public class Send {
    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("192.168.67.129");
        factory.setPort(5672);
        factory.setUsername("root");
        factory.setPassword("root");


        Connection connection = null;

        Channel channel = null;

        try {
            connection  = factory.newConnection();

            channel = connection.createChannel();

            /**
             * 队列
             *  参数 队列名称
             *      是否持久化
             *      是否排外
             *      是否自动删除
             *      属性
             */
            String queueName ="directQueue";
            channel.queueDeclare(queueName, true, false, false, null);

            /**
             * 交换机
             *  1名称
             *  2类型
             *  3是否持久化
             */
            String exchangeName = "directExchange";
            channel.exchangeDeclare(exchangeName, "direct", true);

            /**
             * 队列和交换机绑定
             *  1队列名称
             *  2交换机名称
             *  3绑定的BindingKey
             *  要确保正确绑定和 队列和交互机已经存在
             */
            channel.queueBind(queueName,exchangeName,"directKey");

            String message = "direct测试消息";

            /**
             * 发到mq
             *  1交换机名称
             *  2带的RoutingKey
             *  3消息头
             *  4消息数据
             *
             */
            channel.basicPublish(exchangeName, "directKey", null, message.getBytes());

            System.out.println("消息发送成功---" + message);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (channel ==null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }

            if (connection !=null){
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
